package com.harmontronics.hanma.paas.paas.config;

import com.harmontronics.hanma.paas.paas.domain.app.service.HmProcessService;
import org.flowable.spring.boot.ProcessEngineAutoConfiguration;
import org.flowable.spring.boot.ProcessEngineServicesAutoConfiguration;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;

@Configuration
@ConditionalOnMissingClass("com.harmontronics.hanma.paas.paas.interceptor.TokenValidInterceptor")
public class FlywayConfig implements Ordered {
    @Autowired
    private DataSource dataSource;


    @PostConstruct
    public void migrate() throws IOException {
        System.out.println("flyway loaded");
        ApplicationHome applicationHome = new ApplicationHome(FlywayConfig.class);
        File homeDir = applicationHome.getDir();
        File dbDir = new File(homeDir, "db");
        File migrationDir = new File(dbDir, "migration");
        Flyway flyway = Flyway.configure()
                .dataSource(dataSource)
                .locations("filesystem://"+migrationDir.getAbsolutePath())
                .baselineOnMigrate(true)
                .schemas("public")
                .load();
        flyway.migrate();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
